//
//  LongHelper.m
//  CoachsBook
//
//  Created by huiyong li on 2022/8/18.
//

#import "LongHelper.h"
#import <CommonCrypto/CommonDigest.h>
#import <ifaddrs.h>
#import <net/if.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import <CommonCrypto/CommonDigest.h>
#define LAST_RUN_VERSION_KEY @"last_run_version_of_application"

@implementation LongHelper
+ (UIAlertController *)alertWithTitle:(NSString *)title messgage:(NSString *)message okTitle:(NSString *)okTitle
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *ok = [UIAlertAction actionWithTitle:okTitle style:UIAlertActionStyleDefault handler:nil];
    
    [alert addAction:ok];
    
    return alert;
}

+ (void)poppingAlertWithReminderTitle:(NSString *)reminderStr message:(NSString *)str AndActionTitle:(NSString *)yesStr ActionHandler:(CustomHandler)customHandler ViewController:(UIViewController *)selfVC
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:reminderStr message:str preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:yesStr style:UIAlertActionStyleDefault handler:customHandler];
    [alertController addAction:ok];
    
    [selfVC presentViewController:alertController animated:YES completion:nil];
}
+ (void)poppingAlertWithReminderTitle:(nullable NSString *)reminderStr message:(nullable NSString *)str AndYesActionTitle:(NSString *)yesStr YesActionHandler:(CustomHandler)yesHandler AndCancelActionTitle:(NSString *)cancelStr NoActionHandler:(CustomHandler)noHandler ViewController:(UIViewController *)selfVC
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:reminderStr message:str preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:yesStr style:UIAlertActionStyleDefault handler:yesHandler];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:cancelStr style:UIAlertActionStyleCancel handler:noHandler];
    [alertController addAction:ok];
    [alertController addAction:cancel];
    [selfVC presentViewController:alertController animated:YES completion:nil];
}



+(void)poppingAlertWithReminderTitle:(nullable NSString *)reminderStr message:(nullable NSString *)str AndOneActionTitle:(NSString *)oneStr OneActionHandler:(CustomHandler)oneHandler AndTwoActionTitle:(NSString *)twoStr TwoActionHandler:(CustomHandler)twoHandler AndCancelActionTitle:(NSString *)cancelStr NoActionHandler:(CustomHandler)noHandler ViewController:(UIViewController *)selfVC
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:reminderStr message:str preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *one = [UIAlertAction actionWithTitle:oneStr style:UIAlertActionStyleDefault handler:oneHandler];
    UIAlertAction *two = [UIAlertAction actionWithTitle:twoStr style:UIAlertActionStyleDefault handler:twoHandler];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:cancelStr style:UIAlertActionStyleCancel handler:noHandler];
    [alertController addAction:one];
    [alertController addAction:two];
    [alertController addAction:cancel];
    [selfVC presentViewController:alertController animated:YES completion:nil];
}
//修改第二个登录的字体颜色
+ (void)KPCXWAnotherpoppingAlertWithReminderTitle:(NSString *)reminderStr message:(NSString *)str AndOneActionTitle:(NSString *)oneStr OneActionHandler:(CustomHandler)oneHandler AndTwoActionTitle:(NSString *)twoStr TwoActionHandler:(CustomHandler)twoHandler AndCancelActionTitle:(NSString *)cancelStr NoActionHandler:(CustomHandler)noHandler ViewController:(UIViewController *)selfVC
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:reminderStr message:str preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *one = [UIAlertAction actionWithTitle:oneStr style:UIAlertActionStyleDefault handler:oneHandler];
    UIAlertAction *two = [UIAlertAction actionWithTitle:twoStr style:UIAlertActionStyleDefault handler:twoHandler];
    
    [two setValue:[UIColor redColor] forKey:@"titleTextColor"];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:cancelStr style:UIAlertActionStyleCancel handler:noHandler];
    [alertController addAction:one];
    [alertController addAction:two];
    [alertController addAction:cancel];
    [selfVC presentViewController:alertController animated:YES completion:nil];
}

+ (void)alertWithtTestViewController:(UIViewController *)selfVC
{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Message" message:@"Sorry, it's under development!" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    
        [alert addAction:ok];
    
        [selfVC presentViewController:alert animated:YES completion:nil];
    
    
    
}
+(void)poppingBottomAlertWithReminderTitle:(nullable NSString *)reminderStr message:(nullable NSString *)str AndOneActionTitle:(NSString *)oneStr OneActionHandler:(CustomHandler)oneHandler AndTwoActionTitle:(NSString *)twoStr TwoActionHandler:(CustomHandler)twoHandler AndThreeActionTitle:(NSString *)threeStr ThreeActionHandler:(CustomHandler)threeHandler AndFourActionTitle:(NSString *)fourStr FourActionHandler:(CustomHandler)fourHandler AndFiveActionTitle:(NSString *)fiveStr FiveActionHandler:(CustomHandler)fiveHandler AndCancelActionTitle:(NSString *)cancelStr NoActionHandler:(CustomHandler)noHandler ViewController:(UIViewController *)selfVC
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:reminderStr message:str preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *one = [UIAlertAction actionWithTitle:oneStr style:UIAlertActionStyleDefault handler:oneHandler];
    UIAlertAction *two = [UIAlertAction actionWithTitle:twoStr style:UIAlertActionStyleDefault handler:twoHandler];
    UIAlertAction *three = [UIAlertAction actionWithTitle:threeStr style:UIAlertActionStyleDefault handler:threeHandler];
    UIAlertAction *four = [UIAlertAction actionWithTitle:fourStr style:UIAlertActionStyleDefault handler:fourHandler];
    UIAlertAction *five = [UIAlertAction actionWithTitle:fiveStr style:UIAlertActionStyleDefault handler:fiveHandler];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:cancelStr style:UIAlertActionStyleCancel handler:noHandler];
    [alertController addAction:one];
    [alertController addAction:two];
    [alertController addAction:three];
    [alertController addAction:four];
    [alertController addAction:five];
    [alertController addAction:cancel];
    [selfVC presentViewController:alertController animated:YES completion:nil];
}

+(void)poppingBottomAlertWithReminderTitle:(nullable NSString *)reminderStr message:(nullable NSString *)str AndOneActionTitle:(NSString *)oneStr OneActionHandler:(CustomHandler)oneHandler AndTwoActionTitle:(NSString *)twoStr TwoActionHandler:(CustomHandler)twoHandler AndThreeActionTitle:(NSString *)threeStr ThreeActionHandler:(CustomHandler)threeHandler AndFourActionTitle:(NSString *)fourStr FourActionHandler:(CustomHandler)fourHandler AndCancelActionTitle:(NSString *)cancelStr NoActionHandler:(CustomHandler)noHandler ViewController:(UIViewController *)selfVC
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:reminderStr message:str preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *one = [UIAlertAction actionWithTitle:oneStr style:UIAlertActionStyleDefault handler:oneHandler];
    UIAlertAction *two = [UIAlertAction actionWithTitle:twoStr style:UIAlertActionStyleDefault handler:twoHandler];
    UIAlertAction *three = [UIAlertAction actionWithTitle:threeStr style:UIAlertActionStyleDefault handler:threeHandler];
    UIAlertAction *four = [UIAlertAction actionWithTitle:fourStr style:UIAlertActionStyleDefault handler:fourHandler];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:cancelStr style:UIAlertActionStyleCancel handler:noHandler];
    [alertController addAction:one];
    [alertController addAction:two];
    [alertController addAction:three];
    [alertController addAction:four];
    [alertController addAction:cancel];
    [selfVC presentViewController:alertController animated:YES completion:nil];
}

+(void)poppingBottomAlertWithReminderTitle:(nullable NSString *)reminderStr message:(nullable NSString *)str AndOneActionTitle:(NSString *)oneStr OneActionHandler:(CustomHandler)oneHandler AndTwoActionTitle:(NSString *)twoStr TwoActionHandler:(CustomHandler)twoHandler AndCancelActionTitle:(NSString *)cancelStr NoActionHandler:(CustomHandler)noHandler ViewController:(UIViewController *)selfVC
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:reminderStr message:str preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *one = [UIAlertAction actionWithTitle:oneStr style:UIAlertActionStyleDefault handler:oneHandler];
    UIAlertAction *two = [UIAlertAction actionWithTitle:twoStr style:UIAlertActionStyleDefault handler:twoHandler];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:cancelStr style:UIAlertActionStyleCancel handler:noHandler];
    [alertController addAction:one];
    [alertController addAction:two];
    [alertController addAction:cancel];
    [selfVC presentViewController:alertController animated:YES completion:nil];
}

+(void)poppingBottomAlertWithReminderTitle:(nullable NSString *)reminderStr message:(nullable NSString *)str AndOneActionTitle:(NSString *)oneStr OneActionHandler:(CustomHandler)oneHandler AndTwoActionTitle:(NSString *)twoStr TwoActionHandler:(CustomHandler)twoHandler AndThreeActionTitle:(NSString *)threeStr ThreeActionHandler:(CustomHandler)threeHandler AndCancelActionTitle:(NSString *)cancelStr NoActionHandler:(CustomHandler)noHandler ViewController:(UIViewController *)selfVC
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:reminderStr message:str preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *one = [UIAlertAction actionWithTitle:oneStr style:UIAlertActionStyleDefault handler:oneHandler];
    UIAlertAction *two = [UIAlertAction actionWithTitle:twoStr style:UIAlertActionStyleDefault handler:twoHandler];
    UIAlertAction *three = [UIAlertAction actionWithTitle:threeStr style:UIAlertActionStyleDefault handler:threeHandler];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:cancelStr style:UIAlertActionStyleCancel handler:noHandler];
    [alertController addAction:one];
    [alertController addAction:two];
    [alertController addAction:three];
    [alertController addAction:cancel];
    [selfVC presentViewController:alertController animated:YES completion:nil];
}


+(CGFloat)textHeight:(NSString *)str WithUIFont:(UIFont *)font AndWidth:(CGFloat)width{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
//Attribute传和label设定的一样
    NSDictionary * attributes = @{
                                  NSFontAttributeName:font,
                                  NSParagraphStyleAttributeName: paragraphStyle
                                  };
//这里的size，width传label的宽，高默认都传MAXFLOAT
    CGSize textRect = CGSizeMake(width, MAXFLOAT);
    CGFloat textHeight = [str boundingRectWithSize: textRect
                                           options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                                        attributes:attributes
                                           context:nil].size.height;
    return textHeight;
}


+(CGFloat)textWidth:(NSString *)str WithUIFont:(UIFont *)font AndHeight:(CGFloat)height{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
//Attribute传和label设定的一样
    NSDictionary * attributes = @{
                                  NSFontAttributeName:font,
                                  NSParagraphStyleAttributeName: paragraphStyle
                                  };
//这里的size，width传label的宽，高默认都传MAXFLOAT
    CGSize textRect = CGSizeMake(MAXFLOAT, height);
    CGFloat textWidth = [str boundingRectWithSize: textRect
                                           options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                                        attributes:attributes
                                           context:nil].size.width;
    return textWidth;
}


+ (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}




/** 给控件添加部分圆角
  * @param rect 控件的rect
  * @param corners 需要设置为圆角的角 UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomLeft | UIRectCornerBottomRight | UIRectCornerAllCorners
  * @param cornerRadii 需要设置的圆角大小 CGSize
  * @param roundView 需要设置圆角的控件
**/
+ (void)addCornerWithRoundedRect:(CGRect)rect RoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)cornerRadii roundView:(UIView *)roundView{

    UIBezierPath* rounded = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corners cornerRadii:cornerRadii];
    CAShapeLayer* shape = [[CAShapeLayer alloc] init];
    [shape setPath:rounded.CGPath];
    roundView.layer.mask = shape;
}



//获取缓存大小
+ (NSString *)getCacheSize
{
    //得到缓存路径
        NSString * path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        NSFileManager * manager = [NSFileManager defaultManager];
        CGFloat size = 0;
    //首先判断是否存在缓存文件
        if ([manager fileExistsAtPath:path]) {
            NSArray * childFile = [manager subpathsAtPath:path];
            for (NSString * fileName in childFile) {
                //缓存文件绝对路径
                NSString * absolutPath = [path stringByAppendingPathComponent:fileName];
                size = size + [manager attributesOfItemAtPath:absolutPath error:nil].fileSize;
            }
            //计算SDWebimage5的缓存和系统缓存总和
//            size = size + [[SDImageCache sharedImageCache] totalDiskSize];
        }
        
        double returnSize = size / 1024.0 / 1024.0;
        return [NSString stringWithFormat:@"%.2fM", returnSize];
}

//清理缓存
+ (void)cleanCacheWithSuccess:(void (^)(BOOL success))successBlock
{
    //获取缓存路径
    NSString * path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSFileManager * manager = [NSFileManager defaultManager];
    //判断是否存在缓存文件
    if ([manager fileExistsAtPath:path]) {
        NSArray * childFile = [manager subpathsAtPath:path];
        //逐个删除缓存文件
        for (NSString *fileName in childFile) {
            NSString * absolutPat = [path stringByAppendingPathComponent:fileName];
            [manager removeItemAtPath:absolutPat error:nil];
        }
        
        //删除sdwebimage的缓存
//        [[SDWebImageManager sharedManager].imageCache clearWithCacheType:SDImageCacheTypeAll completion:^{
//            //这里是又调用了得到缓存文件大小的方法，是因为不确定是否删除了所有的缓存，所以要计算一遍，展示出来
//            if ([[self getCacheSize] isEqualToString:@"0.00M"]) {
//                if (successBlock) {
//                    successBlock(YES);
//                }
//        [SVProgressHUD showErrorWithStatus:@"清除缓存成功"];
//            } else {
//                if (successBlock) {
//                    successBlock(NO);
//                }
//        [SVProgressHUD showErrorWithStatus:@"清除缓存失败"];
//            }
//        }];
    }
}


#pragma mark 验证字符串是否为空
+ (BOOL)isBlankString:(NSString *)aStr{
    {
        if (!aStr) {
            return YES;
        }
        if ([aStr isKindOfClass:[NSNull class]]) {
            return YES;
        }
        if (!aStr.length) {
            return YES;
        }
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *trimmedStr = [aStr stringByTrimmingCharactersInSet:set];
        if (!trimmedStr.length) {
            return YES;
        }
        return NO;
    }
}


#pragma mark 计算日期与当前时间的时差
+ (NSInteger)timeWithYearMonthDayCountDown:(NSString *)timestamp
{
    
    NSInteger nowtimeSp = [[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] integerValue];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate* date = [formatter dateFromString:timestamp]; //------------将字符串按formatter转成nsdate
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
    return nowtimeSp-timeSp;
}

#pragma mark 计算日期1与日期2的时差
+ (NSInteger)timeWithYearMonthDayCountDown:(NSString *)timestamp1 AndTiem:(NSString *)timestamp2
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
//    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    [formatter setDateFormat:@"YYYY-MM-dd"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate* date1 = [formatter dateFromString:timestamp1]; //------------将字符串按formatter转成nsdate
    NSDate* date2 = [formatter dateFromString:timestamp2]; //------------将字符串按formatter转成nsdate
    NSInteger timeSp1 = [[NSNumber numberWithDouble:[date1 timeIntervalSince1970]] integerValue];
    NSInteger timeSp2 = [[NSNumber numberWithDouble:[date2 timeIntervalSince1970]] integerValue];
    return timeSp1-timeSp2;
}




+ (CGFloat )createTagButtonToArr:(NSArray *)arr WithViewWidth:(CGFloat)Viewwidth WithwidthNumber:(NSInteger)widthNumber{
    
    // 按钮高度
    CGFloat btnH = 28;
    // 距离左边距
    CGFloat leftX = 5;
    // 距离上边距
    CGFloat topY = 10;
    // 按钮左右间隙
    CGFloat marginX = 5;
    // 按钮上下间隙
    CGFloat marginY = 10;
    // 文字左右间隙
    CGFloat fontMargin = 10;
    
    if (widthNumber == 0) {

        for (int i = 0; i < arr.count; i++) {
            
            UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(marginX + leftX, topY, 100, btnH);
            btn.tag = 100+i;

            // 按钮文字
            [btn setTitle:arr[i] forState:UIControlStateNormal];
            btn.titleLabel.font = [UIFont systemFontOfSize:14];
            // 设置按钮的边距、间隙
            [self setTagButtonMargin:btn fontMargin:fontMargin];
            
            // 处理换行
            if (btn.frame.origin.x + btn.frame.size.width + marginX > Viewwidth) {
                // 换行
                topY += btnH + marginY;
                // 重置
                leftX = 6;
                btn.frame = CGRectMake(marginX + leftX, topY, 100, btnH);
                
                // 设置按钮的边距、间隙
                [self setTagButtonMargin:btn fontMargin:fontMargin];
            }
            CGRect frame = btn.frame;
            frame.size.height = btnH;
            btn.frame = frame;
            leftX += btn.frame.size.width + marginX;
        }
    }
    else
    {
 
        CGFloat btnW = (Viewwidth - marginX*2 - (leftX+marginX)*(widthNumber-1))/widthNumber;
        
        for (int i = 0; i < arr.count; i++) {
            
            UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(marginX + leftX, topY, btnW, btnH);
            btn.tag = 100+i;

            
            // 按钮文字
            [btn setTitle:arr[i] forState:UIControlStateNormal];
            btn.titleLabel.font = [UIFont systemFontOfSize:14];
       
            // 处理换行
            if (btn.frame.origin.x + btn.frame.size.width + marginX > Viewwidth) {
                // 换行
                topY += btnH + marginY;
                
                // 重置
                leftX = 5;
                btn.frame = CGRectMake(marginX + leftX, topY, btnW, btnH);
            }
            
            // 重置高度
            CGRect frame = btn.frame;
            frame.size.height = btnH;
            btn.frame = frame;
            leftX += btn.frame.size.width + marginX;
        }
    }
    
    NSLog(@"cell高度= %f",topY+btnH+10);
    return topY+btnH+10;
}


// 设置按钮的边距、间隙
+ (void)setTagButtonMargin:(UIButton*)btn fontMargin:(CGFloat)fontMargin{
    
    // 按钮自适应
    [btn sizeToFit];
    
    // 重新计算按钮文字左右间隙
    CGRect frame = btn.frame;
    frame.size.width += fontMargin*2;
    btn.frame = frame;
}


+ (BOOL) isFirstLoad {
    
    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleShortVersionString"];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
 
    NSString *lastRunVersion = [defaults objectForKey:LAST_RUN_VERSION_KEY];
 
    if (!lastRunVersion) {
        [defaults setObject:currentVersion forKey:LAST_RUN_VERSION_KEY];
        return YES;
    }
    else if (![lastRunVersion isEqualToString:currentVersion]) {
        [defaults setObject:currentVersion forKey:LAST_RUN_VERSION_KEY];
        return YES;
    }
    return NO;
    
}
//判断是不是刘海屏
+ (BOOL)isNotchScreen {
    if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
        return NO;
    }
    CGSize size = [UIScreen mainScreen].bounds.size;
    NSInteger notchValue = size.width / size.height * 100;
    
    if (216 == notchValue || 46 == notchValue) {
        return YES;
    }
    
    return NO;
}

+ (BOOL)checkStringIsLegal:(NSString *)str {
    if (str == nil) {
        return NO;
    }
    return str.length > 0;
}
+(NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
    return responseJSON;
}
+ (long long)fileSizeAtPath:(NSString*)filePath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

+ (NSString *)getMD5String:(NSString *)str{
    if (str == nil) return nil;
    
//    const char *cstring = str.UTF8String;
//    unsigned char bytes[CC_MD5_DIGEST_LENGTH];
//    CC_MD5(cstring, (CC_LONG)strlen(cstring), bytes);
//
//    NSMutableString *md5String = [NSMutableString string];
//    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
//        [md5String appendFormat:@"%02x", bytes[i]];
//    }
//    return md5String;
    
    return  [self md532BitUpperWith:str];
    
}

//小写
+ (NSString*)md532BitLowerWith:(NSString *)str
{
    const char *cStr = str.UTF8String;
    unsigned char result[16];

    NSNumber *num = [NSNumber numberWithUnsignedLong:strlen(cStr)];
    CC_MD5( cStr,[num intValue], result );

    return [[NSString stringWithFormat:
             @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
}
//大写
+ (NSString*)md532BitUpperWith:(NSString *)str
{
    const char *cStr = str.UTF8String;
    unsigned char result[16];

    NSNumber *num = [NSNumber numberWithUnsignedLong:strlen(cStr)];
    CC_MD5( cStr,[num intValue], result );

    return [[NSString stringWithFormat:
             @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] uppercaseString];
}


+(void)shadowAndCircular:(id)view{
    UIView * newView ;
    UIButton * button;
    if ([view isKindOfClass:[UIView class]]) {
        newView = (UIView *)view;
        newView.layer.masksToBounds = YES;
        newView.layer.cornerRadius = 5.0;
        newView.layer.shadowColor = [UIColor darkGrayColor].CGColor;
        newView.layer.shadowOffset = CGSizeMake(0, 0);
        newView.layer.shadowRadius = 4.0f;
        newView.layer.shadowOpacity = 0.5f;
        newView.layer.masksToBounds = NO;
        newView.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:newView.bounds cornerRadius:newView.layer.cornerRadius].CGPath;
        
    }
    if ([view isKindOfClass:[UIButton class]]) {
        button = (UIButton *)view;
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 5.0;
        button.layer.shadowColor = [UIColor darkGrayColor].CGColor;
        button.layer.shadowOffset = CGSizeMake(0, 0);
        button.layer.shadowRadius = 4.0f;
        button.layer.shadowOpacity = 0.5f;
        button.layer.masksToBounds = NO;
        button.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:button.bounds cornerRadius:button.layer.cornerRadius].CGPath;
        
    }
    
}
+ (BOOL)isExistFile:(NSString *)fileName {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager fileExistsAtPath:fileName];
}

+ (BOOL)checkDictionaryIsLegal:(NSDictionary *)dic allowEmpty:(BOOL)allow {
    if (dic == nil) {
        return NO;
    }
    
    BOOL result = YES;
    
    for (id key in dic) {
        if ([dic[key] isKindOfClass:[NSNull class]]) {
            result = NO;
            break;
        }
        
        if (!allow && [dic[key] isKindOfClass:[NSString class]]) {
            NSString *mapKey = dic[key];
            if (![LongHelper checkStringIsLegal:mapKey]) {
                result = NO;
                break;
            }
        }
    }
    
    return result;
}

+ (NSDictionary *)filterDicForKeys:(NSArray *)keys dic:(NSDictionary *)dic {
    NSMutableDictionary *result = [NSMutableDictionary dictionaryWithCapacity:keys.count];
    
    for (NSString *key in keys) {
        if (dic[key] == nil) {
            continue;
        }
        result[key] = dic[key];
    }
    
    return [result copy];
}

+ (NSString *)JSONEncode:(id)dic
{
    return [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dic options:kNilOptions error:nil] encoding:NSUTF8StringEncoding];
}

+ (id)JSONDecode:(NSString *)json
{
    return [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
}

+ (NSInteger)timestamp
{
    return [NSDate timeIntervalSinceReferenceDate];
}

+ (NSDate *)timeStringToDate:(NSString *)dateString{
    // 日期格式化类
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    // 设置日期格式 为了转换成功
    format.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    return [format dateFromString:dateString];
}
+ (NSString*)MD5ofData:(NSData *)fileData
{
    // Create byte array of unsigned chars
    unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
    
    // Create 16 byte MD5 hash value, store in buffer
    CC_MD5(fileData.bytes, (CC_LONG)fileData.length, md5Buffer);
    
    // Convert unsigned char buffer to NSString of hex values
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x",md5Buffer[i]];
    
    return output;
}

//+ (NSString *)storeArticleFile:(NSString *)content
//{
//    [FM createDirectoryAtPath:ArticleFilePath withIntermediateDirectories:NO attributes:nil error:nil];
//    NSString *articleFile = [ArticleFilePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%ld.art", [Utils timestamp]]];
//    [[content dataUsingEncoding:NSUTF8StringEncoding] writeToFile:articleFile atomically:YES];
//    return articleFile;
//}

//+ (NSString*)STT:(NSString *)string
//{
//    NSString *identifier = [[NSLocale preferredLanguages] objectAtIndex:0];
//    if ([identifier isEqualToString:@"zh-Hant"]){
//        return [[OBCConvertor getInstance] s2t:string];
//    } else {
//        return string;
//    }
//}

//1-douban 2-tieba 3-tianya 4-maopu
+ (NSString *)nameOfWebCode:(NSInteger)code
{
    switch (code) {
        case 1:
            return @"豆瓣";
            break;
        case 2:
            return @"百度贴吧";
            break;
        case 3:
            return @"天涯";
            break;
        case 4:
            return @"猫扑";
            break;
        default:
            return @"";
            break;
    }
}

+ (NSString *)formatDateFromTimestamp:(NSInteger)unixtime
{
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd"];
    return [format stringFromDate:[NSDate dateWithTimeIntervalSince1970:unixtime]];
}

+ (NSString *)formatDateFromTimestampOfBookMark:(NSInteger)time
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *format = [NSDateFormatter new];
    [format setDateFormat:@"yyyy-MM-dd HH:mm"];
    return [format stringFromDate:date];
}

+ (NSString *)getTimeStringforDate:(NSDate *)date
{
    if (!date){
        return @"";
    }
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *today = [NSDate date];
    NSDateComponents *dateComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekOfYear | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute fromDate:date];
    NSDateComponents *todayComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekOfYear | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute fromDate:today];
    if (dateComponents.year == todayComponents.year && dateComponents.month == todayComponents.month && dateComponents.day == todayComponents.day){
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm"];
        [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
        return [dateFormatter stringFromDate:date];
    } else if ((dateComponents.year == todayComponents.year) && (dateComponents.month == todayComponents.month) && (dateComponents.day == todayComponents.day - 1)){
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm"];
        [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
        return [NSString stringWithFormat:@"昨天 %@", [dateFormatter stringFromDate:date]];
    } else if ((dateComponents.year == todayComponents.year) && (dateComponents.month == todayComponents.month) && (dateComponents.day == todayComponents.day - 2)){
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm"];
        [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
        return [NSString stringWithFormat:@"前天 %@", [dateFormatter stringFromDate:date]];
    } else if ((dateComponents.year == todayComponents.year)){
        NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
        [dateFormatter1 setDateFormat:@"MM-dd"];
        [dateFormatter1 setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
        return [dateFormatter1 stringFromDate:date];
    } else {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yy-MM-dd HH:mm"];
        [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
        return [dateFormatter stringFromDate:date];
    }
}
+ (NSInteger)calcDaysFromBegin:(NSDate *)beginDate end:(NSDate *)endDate
{
    // 创建日期格式化对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    // 取两个日期对象的时间间隔
    // 这里的 NSTimeInterval 并不是对象，是基本型，其实是double 类型，是由 C 定义的: typedef double NSTimeInterval;
    NSTimeInterval time = [endDate timeIntervalSinceDate:beginDate];
    int days = ((int)time)/(3600 * 24);
    return days;
}

+ (NSMutableArray*)arrayOfString:(NSString*)string
{
    NSMutableArray *tmpArray = [[NSMutableArray alloc] initWithCapacity:[string length]];
    for (int i=0; i < [string length]; i++) {
        NSString *ichar  = [NSString stringWithFormat:@"%C", [string characterAtIndex:i]];
        [tmpArray addObject:ichar];
    }
    return tmpArray;
}

+ (UIImage *)imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return img;
}

//http://stackoverflow.com/questions/2658738/the-simplest-way-to-resize-an-uiimage
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize
{
    //UIGraphicsBeginImageContext(newSize);
    // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
    // Pass 1.0 to force exact pixel size.
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 1.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
+ (NSString *)reviseString:(NSString *)str{
    //直接传入精度丢失有问题的Double类型
    double conversionValue = [str doubleValue];
    NSString *doubleString = [NSString stringWithFormat:@"%lf", conversionValue];
    NSDecimalNumber *decNumber = [NSDecimalNumber decimalNumberWithString:doubleString];
    return [decNumber stringValue];
}
+ (NSString *)orderDateString:(NSDate*)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    return [dateFormatter stringFromDate:date];
}



+ (NSInteger)calDuringTime:(NSDate *)startDate end:(NSDate *)endDate
{
    NSInteger tmp = (([endDate timeIntervalSinceDate:startDate]+(20*3600)) / (3600 * 24));
    return (tmp == 0 ? 1 : tmp) + 1;
}

+ (NSString *)weekdayText:(NSInteger)week
{
    switch (week) {
        case 1:
            return @"一";
            break;
        case 2:
            return @"二";
            break;
        case 3:
            return @"三";
            break;
        case 4:
            return @"四";
            break;
        case 5:
            return @"五";
            break;
        case 6:
            return @"六";
            break;
        case 7:
            return @"日";
            break;
        case 0:
            return @"日";
            break;
            
        default:
            break;
    }
    return @"";
}

+ (void)originImage:(UIImage *)image scaleToSize:(CGSize)size returnImage:(void (^)(UIImage *image))complete
{
    dispatch_queue_t myQueue = dispatch_queue_create("com.uchang.resize.image",NULL);
    dispatch_async(myQueue, ^{
        CGSize newSize;
        if (image.size.width > size.width){
            newSize.height = size.width / image.size.width * image.size.height;
            newSize.width = size.width;
        } else if (image.size.height > size.height){
            newSize.height = size.height;
            newSize.width = size.height / image.size.height * image.size.width;
        } else {
            newSize = size;
        }
        // 创建一个bitmap的context
        // 并把它设置成为当前正在使用的context
        UIGraphicsBeginImageContextWithOptions(newSize, YES, 0);
        
        // 绘制改变大小的图片
        [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
        
        // 从当前context中创建一个改变大小后的图片
        UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
        
        // 使当前的context出堆栈
        UIGraphicsEndImageContext();
        
        // 返回新的改变大小后的图片
        dispatch_async(dispatch_get_main_queue(), ^{
            if (complete) complete(scaledImage);
        });
    });
}

+ (NSString *)showDistance:(NSInteger)meter
{
    if (meter < 1000){
        return [NSString stringWithFormat:@"%ld米", (long)meter];
    } else {
        return [NSString stringWithFormat:@"%0.2f公里", ((float)meter/1000)];
    }
}
+ (NSString *)getWeekDayFordate:(NSDate *)date{
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; // 指定日历的算法
    NSDateComponents *comps = [calendar components:NSCalendarUnitWeekday fromDate:date];// 1 是周日，2是周一 3.以此类推
    NSNumber * weekNumber = @([comps weekday]);
    NSInteger weekInt = [weekNumber integerValue];
    NSString *weekDayString = @"(周一)";
    switch (weekInt) {
        case 1:{weekDayString = @"(周日)";}break;case 2:{weekDayString = @"(周一)";}break;case 3:{weekDayString = @"(周二)";}break;case 4:{weekDayString = @"(周三)";}break;case 5:{weekDayString = @"(周四)";}break;case 6:{weekDayString = @"(周五)";}break;case 7:{weekDayString = @"(周六)";}break;default:break;}return weekDayString;
    
}
/**
 获取距离当前多少周的日期数组
 
 @param weeks 0 当周
 @return [3月,6,7,8,9,10,11,12]
 */
+ (NSArray *)getDatesSinceCurence:(NSInteger)weeks {
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:8];
    
    NSDate *date = [[NSDate date] dateByAddingTimeInterval:60 * 60 * 24 * 7 * (weeks - 1)];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitWeekday | NSCalendarUnitDay | NSCalendarUnitYear | NSCalendarUnitMonth fromDate:date];
    
    NSInteger weekdayToday = [components weekday];
    
    NSInteger daysToMonday = (9 - weekdayToday) % 7;
    NSDate *nextMonday = [date dateByAddingTimeInterval:60 * 60 * 24 * daysToMonday];
    
    NSDateComponents *nextComponents = [calendar components:NSCalendarUnitWeekday | NSCalendarUnitDay | NSCalendarUnitYear | NSCalendarUnitMonth fromDate:nextMonday];
    
    NSInteger month = nextComponents.month;
    NSInteger day = nextComponents.day;
    
    [result addObject:[NSString stringWithFormat:@"%ld月", (long)month]];
    [result addObject:[NSString stringWithFormat:@"%ld", (long)day]];
    
    for (int i = 1; i < 7; i++) {
        NSDate *nextDay = [nextMonday dateByAddingTimeInterval:60 * 60 * 24 * i];
        NSDateComponents *nextdayComponents = [calendar components:NSCalendarUnitDay fromDate:nextDay];
        [result addObject:[NSString stringWithFormat:@"%ld", (long)[nextdayComponents day]]];
    }
    
    return result;
}

+ (NSString *)thumbnailURL:(NSString *)url
{
    if ([UIScreen mainScreen].bounds.size.width >= 414){
        return [NSString stringWithFormat:@"%@_i6p", url];
    } else if ([UIScreen mainScreen].bounds.size.width >= 375){
        return [NSString stringWithFormat:@"%@_i6", url];
    } else {
        return [NSString stringWithFormat:@"%@_thumb", url];
    }
}

+(UIImage *)coreBlurImage:(UIImage *)image withBlurNumber:(CGFloat)blur
{
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *inputImage= [CIImage imageWithCGImage:image.CGImage];
    //设置filter
    CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [filter setValue:inputImage forKey:kCIInputImageKey]; [filter setValue:@(blur) forKey: @"inputRadius"];
    //模糊图片
    CIImage *result=[filter valueForKey:kCIOutputImageKey];
    CGImageRef outImage=[context createCGImage:result fromRect:[result extent]];
    UIImage *blurImage=[UIImage imageWithCGImage:outImage];
    CGImageRelease(outImage);
    return blurImage;
}
+ (NSString *)getNowTimeTimestamp{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-ddHH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    
    return timeSp;
    
}
+(NSString *)toJSONData:(id)theData{
    
    //    NSError *error = nil;
    NSString *jsonString;
    NSData * jsonData=[NSJSONSerialization dataWithJSONObject:theData options:NSJSONWritingPrettyPrinted error:nil];
    
    if ([jsonData length]){
        
        jsonString = [[NSString alloc] initWithData:jsonData
                                           encoding:NSUTF8StringEncoding];
    }else{
        
    }
    return jsonString;
}
+ (BOOL)validateNumber:(NSString*)number{
    BOOL res = YES;
    NSCharacterSet *tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            
            break;
        }
        i++;
    }
    return res;
}
+ (BOOL)isFileExist:(NSString *)fileName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    NSLog(@"这个文件已经存在：%@",result?@"是的":@"不存在");
    return result;
}
+ (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

+ (NSString *)changeAge:(NSString *)dateString{
    NSInteger timeInterval;
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    [formatter setTimeZone:timeZone];
    NSString *current = [formatter stringFromDate:[NSDate date]];
    NSDate *currentDate = [formatter dateFromString:current];
    NSDate *date = [formatter dateFromString:dateString];
    
    NSTimeInterval checkTime = [date timeIntervalSince1970];
    NSTimeInterval currenttime = [currentDate timeIntervalSince1970];
    timeInterval = (checkTime-currenttime)/(60*60*24);
    NSDate * fromDate = [NSDate date];
    NSDate * toDate = [NSDate date];
    if (timeInterval >0) {
        toDate = date;
    }else{
        fromDate = date;
    }
    // 当前日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 需要对比的时间数据
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth
    | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    // 对比时间差
    NSDateComponents *dateCom = [calendar components:unit fromDate:fromDate toDate:toDate options:0];
    NSString * string = [NSString stringWithFormat:@"%ld岁%ld个月",(long)dateCom.year,(long)dateCom.month];
    if (dateCom.year == 0) {
        string = [NSString stringWithFormat:@"%ld个月",(long)dateCom.month];
    }
    if (dateCom.month == 0) {
        string = [NSString stringWithFormat:@"%ld岁",(long)dateCom.year];
    }
    if (dateCom.month == 0 && dateCom.year == 0) {
        string = [NSString stringWithFormat:@"1个月"];
    }
    
    NSLog(@"年龄:%@",string);
    return string;
}
+ (BOOL)isWiFiEnabled {
    
    NSCountedSet * cset = [NSCountedSet new];
    
    struct ifaddrs *interfaces;
    
    if( ! getifaddrs(&interfaces) ) {
        for( struct ifaddrs *interface = interfaces; interface; interface = interface->ifa_next) {
            if ( (interface->ifa_flags & IFF_UP) == IFF_UP ) {
                [cset addObject:[NSString stringWithUTF8String:interface->ifa_name]];
            }
        }
    }
    return [cset countForObject:@"awdl0"] > 1 ? YES : NO;
}
+ (NSString *)getTimeStringYMDforDateString:(NSString *)dateString{
    
    
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:dateString];
    NSDateFormatter *newdateFormatter = [[NSDateFormatter alloc] init];
    [newdateFormatter setDateFormat:@"YYYY.MM.dd"];
    return [newdateFormatter stringFromDate:date];
}


+ (NSString *)getTimeStringforDateString:(NSString *)dateString{
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:dateString];
    NSDateFormatter *newdateFormatter = [[NSDateFormatter alloc] init];
    [newdateFormatter setDateFormat:@"YYYY.MM.dd"];
    return [newdateFormatter stringFromDate:date];
}
+ (NSString *)getTimeStringforYMDHMSString:(NSString *)dateString{
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:dateString];
    NSDateFormatter *newdateFormatter = [[NSDateFormatter alloc] init];
    [newdateFormatter setDateFormat:@"YYYYMMddHHmmss"];
    return [newdateFormatter stringFromDate:date];
}
//将时间格式转成MM/DD输出
+ (NSString *)getTimeStringMDforDateString:(NSString *)dateString
{
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSDate *date = [dateFormatter dateFromString:dateString];
    NSDateFormatter *newdateFormatter = [[NSDateFormatter alloc] init];
    [newdateFormatter setDateFormat:@"MM/dd"];
    return [newdateFormatter stringFromDate:date];
}

//将时间YYYY-MM-DD格式转成周几输出
+ (NSString *)getTimeStringforWeekString:(NSString *)dateString
{
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSDate *date = [dateFormatter dateFromString:dateString];
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];//NSGregorianCalendar
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    [calendar setTimeZone: timeZone];
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;//NSWeekdayCalendarUnit
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:date];
    return [weekdays objectAtIndex:theComponents.weekday];
}


//将某个时间转化成 时间戳
#pragma mark - 将某个时间转化成 时间戳

+(NSInteger)timeSwitchTimestamp:(NSString *)formatTime andFormatter:(NSString *)format{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:format]; //(@"YYYY-MM-dd hh:mm:ss") ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate* date = [formatter dateFromString:formatTime]; //------------将字符串按formatter转成nsdate
    
    //时间转时间戳的方法:
    
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
    return timeSp;
    
}
#pragma mark - 计算时间
+ (NSString *)lastTimeOfComment:(NSDate *)date{
    
    NSString *str = @" ";
    NSDate *nowDate = [NSDate date];
    NSTimeInterval timeInterval = [nowDate timeIntervalSinceDate:date];
    //北京时间加8小时  除以86400得到的是天数
    if ((timeInterval ) / 86400 > 1 && (timeInterval ) / 86400 < 30) {
        
        NSString *min2 =  [NSString stringWithFormat:@"%d天前",(int)(timeInterval ) / 86400];
        str = min2;
    }
    //今天
    else if ((timeInterval ) / 86400 < 1) {
        
        if (timeInterval < 60) {
            str = @"刚刚";
        }
        else if(60 < timeInterval && timeInterval < 3600){
            NSString *min2 =  [NSString stringWithFormat:@"%d分钟前",(int)timeInterval/60];
            str = min2;
        }
        else{
            NSString *min2 =  [NSString stringWithFormat:@"%d小时前",(int)timeInterval/60/60];
            str = min2;
        }
    }
    //一个月前
    else if ((timeInterval ) / 86400 > 30) {
        //        NSString *min2 =  [NSString stringWithFormat:@"%d个月前",(int)(timeInterval) / 2592000];
        //        str = min2;
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
        str = [formatter stringFromDate:date];
    }
    return str;
}

//根据高度度求宽度  text 计算的内容  Height 计算的高度 font字体大小
+ (CGFloat)getWidthWithText:(NSString *)text height:(CGFloat)height font:(UIFont *)font{
    
    if (!text || !font) {
        return 0;
    }
    CGRect rect = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, height)
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:@{NSFontAttributeName:font}
                                     context:nil];
    return rect.size.width;
}
+ (NSString *)changeFloatWithString:(NSString *)stringFloat
{
    const char *floatChars = [stringFloat UTF8String];
    NSUInteger length = [stringFloat length];
    NSUInteger zeroLength = 0;
    NSInteger i = length-1;
    for(; i>=0; i--)
    {
        if(floatChars[i] == '0') {
            zeroLength++;
        } else {
            if(floatChars[i] == '.')
                i--;
            break;
        }
    }
    NSString *returnString;
    if(i == -1) {
        returnString = @"0";
    } else {
        returnString = [stringFloat substringToIndex:i+1];
    }
    return returnString;
}

+ (NSString *)changeFloatWithFloat:(NSString *)floatString
{
    return [self changeFloatWithString:floatString];
}
+ (NSString *)numberSuitScanf:(NSString*)number
{
    
    NSMutableString *phoneStr = [NSMutableString stringWithString:number];
    
    NSString *regex = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    // 判断当前字符串是否为手机号
    BOOL isMatch = [pred evaluateWithObject:phoneStr];
    if (isMatch) {
        [phoneStr replaceCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    }
    
    return [NSString stringWithString:phoneStr];
}

+ (NSString *)base64EncodeString:(NSString *)string{
    //1、先转换成二进制数据
      NSData *data =[string dataUsingEncoding:NSUTF8StringEncoding];
      //2、对二进制数据进行base64编码，完成后返回字符串
      return [data base64EncodedStringWithOptions:0];
}
+ (NSString *)base64EncodeImage:(UIImage *)image{
    NSData *data = UIImageJPEGRepresentation(image, 1.0f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return encodedImageStr;
}
+(NSString *)sha1:(NSString *)string{
    const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
     NSData *data = [NSData dataWithBytes:cstr length:string.length];

     uint8_t digest[CC_SHA1_DIGEST_LENGTH];
     CC_SHA1(data.bytes, (unsigned int)data.length, digest);
     NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];

     for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
         [output appendFormat:@"%02x", digest[i]];
     }
     return output;
}
+ (NSInteger)getSuspendTime:(NSInteger)ids{
    
    switch (ids) {
        case 0:
            return 999999999;
            break;
        case 1:
// 测试专用 上线后改回来
            return 600;
            break;
        case 2:
            return 1200;
            break;
        case 3:
            return 1800;
            break;
        case 4:
            return 3600;
            break;
        default:
            break;
    }
    return 999999999;
}
+ (NSString *)iphoneType {
    struct utsname systemInfo;
    uname(&systemInfo);

    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];

    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";

    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";

    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";

    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";

    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";

    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";

    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";

    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";

    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";

    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";

    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";

    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";

    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";

    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";

    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";

    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";

    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";

    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";

    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";//国行、日版、港行

    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";//港行、国行
    if ([platform isEqualToString:@"iPhone9,3"])    return @"iPhone 7";//美版、台版
    if ([platform isEqualToString:@"iPhone9,4"])    return @"iPhone 7 Plus";//美版、台版

    if ([platform isEqualToString:@"iPhone10,1"])   return @"iPhone 8";//国行(A1863)、日行(A1906)

    if ([platform isEqualToString:@"iPhone10,4"])   return @"iPhone 8";//美版(Global/A1905)

    if ([platform isEqualToString:@"iPhone10,2"])   return @"iPhone 8 Plus";//国行(A1864)、日行(A1898)

    if ([platform isEqualToString:@"iPhone10,5"])   return @"iPhone 8 Plus";//美版(Global/A1897)

    if ([platform isEqualToString:@"iPhone10,3"])   return @"iPhone X";//国行(A1865)、日行(A1902)

    if ([platform isEqualToString:@"iPhone10,6"])   return @"iPhone X";//美版(Global/A1901)

    if ([platform isEqualToString:@"iPhone11,8"])   return @"iPhone XR";
    if ([platform isEqualToString:@"iPhone11,2"])   return @"iPhone XS";
    if ([platform isEqualToString:@"iPhone11,6"])   return @"iPhone XS Max";
    if ([platform isEqualToString:@"iPhone11,4"])   return @"iPhone XS Max";

    return platform;
}

+ (BOOL)checkPhoneNumber:(NSString *)phoneNumber {
    NSString *Regex=@"^1[0-9][0-9]{9}$";
    NSPredicate *phoneNumberTest=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",Regex];
    return [phoneNumberTest evaluateWithObject:phoneNumber];
}
 + (BOOL) theStringIsAllNumbers:(NSString*)str{
     NSScanner* scan = [NSScanner scannerWithString: str];
     int val;
     return[scan scanInt:&val] && [scan isAtEnd];
 }
+ (BOOL)isNum:(NSString *)checkedNumString {
    NSCharacterSet *str=[[NSCharacterSet characterSetWithCharactersInString:@".1234567890-"] invertedSet];
    NSString *filter=[[checkedNumString componentsSeparatedByCharactersInSet:str] componentsJoinedByString:@""];
    BOOL isNum = [checkedNumString isEqualToString:filter];
    return isNum;
}



/**
 得到当前时间之后N天的日期
 @param day N天
 @return return value description
 */
+ (NSDate *)getTimeAfterNowDate:(NSDate*)nowDate WithDay:(NSInteger)day
{
    NSDate *theDate;
    
    if(day!=0)
    {
        NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
        
        theDate = [nowDate initWithTimeIntervalSinceNow: +oneDay*day ];
        //or
        //theDate = [nowDate initWithTimeIntervalSinceNow: -oneDay*day ];
    }
    else
    {
        theDate = nowDate;
    }
    return theDate;
}


#pragma mark 获取第nowDate在当天的分钟数
+ (NSInteger)getHoursTimeAfterNowDate:(NSDate*)nowDate
{
    NSInteger hours;
    
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"H"];
    NSString *time = [dateFormatter stringFromDate:nowDate];
    hours  = 60*[time intValue];
    [dateFormatter setDateFormat:@"m"];
    hours = hours + [[dateFormatter stringFromDate:nowDate] intValue];
    return hours;
}




+ (NSString *)getInternetDate
{
    //NSString *urlString = @"https://www.baidu.com";
    NSString *urlString = @"https://shijian.beijing-time.org";
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString: urlString]];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setTimeoutInterval: 2];
    [request setHTTPShouldHandleCookies:FALSE];
    [request setHTTPMethod:@"GET"];
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    //NSLog(@">>>>> response :%@",response);
    NSString *date = [[response allHeaderFields] objectForKey:@"Date"];
    
    //NSLog(@">>>>> date :%@",date);
    date = [date substringFromIndex:5];
    date = [date substringToIndex:[date length]-4];
    //NSLog(@">>>>> date :%@",date);
    NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];
    dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
//    dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh-CHS"];
    [dMatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];
    NSDate *netDate = [[dMatter dateFromString:date] dateByAddingTimeInterval:60*60*8];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: netDate];
    NSDate *localeDate = [netDate  dateByAddingTimeInterval: interval];
    //NSLog(@">>>>> localeDate :%@",localeDate);
    NSString *tmpDate = [NSString stringWithFormat:@"%@",localeDate];
    tmpDate = [tmpDate stringByReplacingOccurrencesOfString:@" +0000" withString:@""];
    //NSLog(@">>>>> localeDate :%@",tmpDate);
    
    NSDateFormatter *format1=[[NSDateFormatter alloc]init];
    [format1 setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    NSDate *nowDate = [format1 dateFromString:tmpDate];
    NSString *nowDate_ = [format1 stringFromDate:nowDate];
    return nowDate_;
}


+ (NSString *)getInternetHoursDate
{
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"H"];
    NSString *time = [dateFormatter stringFromDate:[NSDate date]];
    return time;
    
}


/**
 * 验证身份证号码是否正确的方法
 *
 * @param IDNumber 传进身份证号码字符串
 *
 * @return 返回YES或NO表示该身份证号码是否符合国家标准
 */
+(BOOL)isCorrect:(NSString *)IDNumber
{
  NSMutableArray *IDArray = [NSMutableArray array];
  // 遍历身份证字符串,存入数组中
  for (int i = 0; i < 18; i++) {
    NSRange range = NSMakeRange(i, 1);
    NSString *subString = [IDNumber substringWithRange:range];
    [IDArray addObject:subString];
  }
  // 系数数组
  NSArray *coefficientArray = [NSArray arrayWithObjects:@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2", nil];
  // 余数数组
  NSArray *remainderArray = [NSArray arrayWithObjects:@"1", @"0", @"X", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2", nil];
  // 每一位身份证号码和对应系数相乘之后相加所得的和
  int sum = 0;
  for (int i = 0; i < 17; i++) {
    int coefficient = [coefficientArray[i] intValue];
    int ID = [IDArray[i] intValue];
    sum += coefficient * ID;
  }
  // 这个和除以11的余数对应的数
  NSString *str = remainderArray[(sum % 11)];
  // 身份证号码最后一位
  NSString *string = [IDNumber substringFromIndex:17];
    if ([string isEqualToString:@"x"]) {
        string = @"X";
    }
  // 如果这个数字和身份证最后一位相同,则符合国家标准,返回YES
  if ([str isEqualToString:string]) {
    return YES;
  } else {
    return NO;
  }
}


+ (NSString *)formatDateFromTimestampAddSeconds:(NSInteger)time
{
    NSInteger timeSp = [[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] integerValue];
    timeSp = timeSp + time;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeSp];
    NSDateFormatter *format = [NSDateFormatter new];
    [format setDateFormat:@"yyyy-MM-dd HH:mm"];
    return [format stringFromDate:date];
}




#pragma mark 验证字符串是否包含敏感词汇
+ (BOOL)isViolationsString:(NSString *)aStr
{
    
    NSArray *strarr = @[@"自杀",@"毛泽东",@"习近平"];
    
    for (NSString *str in strarr) {
        
        if ([aStr containsString:str]) {
            NSLog(@"包含");
            return YES;
        } else {
            NSLog(@"不包含");
        }
    }
    return NO;
}


@end
